package com.touchfired.common.core.listener.impl;

import com.touchfired.common.constants.ClientInfo;
import com.touchfired.common.constants.GameRule;
import com.touchfired.common.constants.RoomInfo;
import com.touchfired.common.context.ServerContext;
import com.touchfired.common.core.callback.Callback;
import com.touchfired.common.core.event.impl.ChatEvent;
import com.touchfired.common.core.event.impl.RoomCreateEvent;
import com.touchfired.common.core.event.impl.RoomQuitEvent;
import com.touchfired.common.core.event.impl.SendRoomDetailEvent;
import com.touchfired.common.core.listener.BaseListener;
import com.touchfired.common.core.publisher.impl.EventPublisher;
import com.touchfired.common.params.CreateRoomParams;
import com.touchfired.common.utils.RoomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;

/**
 * 退出房间 监听器
 *
 * @author 幸佳俊
 */
@Component
public class RoomQuitListener extends BaseListener<RoomQuitEvent> {

    private final ServerContext serverContext;
    private final EventPublisher publisher;
    public RoomQuitListener(ServerContext serverContext, EventPublisher publisher) {
        this.serverContext = serverContext;
        this.publisher = publisher;
    }

    @Override
    public void onEvent(RoomQuitEvent roomQuitEvent, Callback callback) {
        ClientInfo clientInfo = roomQuitEvent.getClientInfo();
        RoomInfo roomInfo = roomQuitEvent.getRoomInfo();

        LinkedList<String> roomClientLongIds = roomInfo.getRoomClientLongIds();
        boolean isQuit = roomClientLongIds.removeIf(clientInfo.getLongId()::equals);
        if (isQuit) {
            clientInfo.setRoomId(null);
            serverContext.updateClientInfo(clientInfo);
            serverContext.updateRoomInfo(roomInfo);
            if (roomClientLongIds.size() == 0) {
                serverContext.removeRoomInfo(roomInfo.getRoomId());
            } else {
                List<ClientInfo> roomClients = RoomUtil.getRoomClients(roomClientLongIds);
                publisher.publish(new ChatEvent(clientInfo, roomClients, "退出房间"));
                publisher.publish(new SendRoomDetailEvent(roomInfo));
            }
        }
    }

}
